#include "stdafx.h"
#include "dr_api.h"
#include <fstream>
#include <string.h>

using namespace std;
static void event_exit(void);
static bool event_pre_syscall(void *drcontext, int sysnum);
static void event_post_syscall(void *drcontext, int sysnum);
static char* REG;
static file_t ft;

DR_EXPORT void dr_init(client_id_t id)
{
	ft=dr_open_file("C:/test.txt",DR_FILE_WRITE_APPEND);
	if(INVALID_FILE==ft)
	{
		dr_messagebox("OpenFail.");
		exit(1);
	}
	dr_messagebox("OpenSuccess.");
	dr_register_pre_syscall_event(event_pre_syscall);
	dr_register_post_syscall_event(event_post_syscall);
    dr_register_exit_event(event_exit);
}

static bool event_pre_syscall(void *drcontext, int sysnum)
{
	switch(sysnum){
	case 0x00b7:
		REG=(char*)dr_syscall_get_param(drcontext,5);
		break;
	case 0x00b8:
		REG=(char*)dr_syscall_get_param(drcontext,5);
		break;
	case 0x00b9:
		REG=(char*)dr_syscall_get_param(drcontext,3);
		break;
	case 0x00ba:
		REG=(char*)dr_syscall_get_param(drcontext,2);
		break;
	default:
		break;
	}
	return true;
}

static void event_post_syscall(void *drcontext, int sysnum)
{
	string result="";	
	switch(sysnum){
	case 0x00b7: 
		result+="0x00b7:buf:";
		result+=REG;
		result+="\n";
		dr_write_file(ft,result.c_str(),result.size());
		break;
	case 0x00b8:
		result+="0x00b8:buf:";
		result+=REG;
		result+="\n";
		dr_write_file(ft,result.c_str(),result.size());
		break;
	case 0x00b9:
		result+="0x00b9:buf:";
		result+=REG;
		result+="\n";
		dr_write_file(ft,result.c_str(),result.size());
		break;
	case 0x00ba:
		result+="0x00ba:buf:";
		result+=REG;
		result+="\n";
		dr_write_file(ft,result.c_str(),result.size());
		break;
	default:
		break;
	}
}
static void event_exit(void)
{
//	FILE*fp;
//	if((fp=fopen("test","w"))==NULL)
//		exit(1);
//	fputs(result.c_str(),fp);
	dr_close_file(ft);
	dr_messagebox("Exit.");
}